package com.fqcar.fqdf.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.fqcar.fqdf.DFApp;
import com.fqcar.fqdf.R;
import com.fqcar.fqdf.RemoteAPI;
import com.fqcar.fqdf.core.http.GofunErrorListener;
import com.fqcar.fqdf.core.http.ResponseEntityRequest;
import com.fqcar.fqdf.core.http.ResponseError;
import com.fqcar.fqdf.entity.AppUpdate;
import com.fqcar.fqdf.entity.ResponseEntity;
import com.fqcar.fqdf.service.VolleySingleton;
import com.fqcar.fqdf.ui.NormalHomeActivity;
import com.fqdf.framework.android.util.FileUtil;

import java.io.File;
import java.io.IOException;

public class DFUpdate {

    private Boolean checkUpdating = false;
    private Activity baseRequestActivity;
    private AppUpdate app;
    private static DFUpdate update;

//	private Boolean check = false;

    public DFUpdate(Activity act) {
        this.baseRequestActivity = act;
    }

    /*public synchronized static HCUpdate getInstance(BaseActivity activity){
        if(null == update){
			update = new HCUpdate(activity);
		}
		return update;
	}*/

    public void requestUpdate() {
//		this.check = check;
        synchronized (this) {
            if (!checkUpdating) {
                checkUpdating = true;
                ResponseEntityRequest request = new ResponseEntityRequest(RemoteAPI.SYS_APP_UPDATE, null, userCheckupdateListener, userCheckupdateError, baseRequestActivity);
                VolleySingleton.getInstance().addRequest(request);
            } else {
                Toast.makeText(baseRequestActivity, "更新中,请稍后...", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private Response.Listener<ResponseEntity> userCheckupdateListener = new Response.Listener<ResponseEntity>() {
        @Override
        public void onResponse(ResponseEntity response) {
            if (null != response.modelData.get("appVersionInfo")) {
                app = JSON.parseObject(JSON.toJSONString(response.modelData.get("appVersionInfo")), AppUpdate.class);
                new AppUpdateDialog(baseRequestActivity).show();
            } else {
				/*if(check){
					Toast.makeText(baseRequestActivity, "当前是最新版本!", Toast.LENGTH_LONG).show();
				}*/
                checkUpdating = false;
            }
        }
    };
    private GofunErrorListener userCheckupdateError = new GofunErrorListener() {
        @Override
        public void onFailure(ResponseError error) {
            commonErrorListener.onFailure(error);
            checkUpdating = false;
        }
    };

    public GofunErrorListener commonErrorListener = new GofunErrorListener() {
        @Override
        public void onFailure(ResponseError error) {
            if (error.isServerError) {
                if (error.code == ResponseEntity.TOKEN_FAIL) {
                    executeTokenFailue();
                } else {
                    //提示服务器给出的错误
                    DialogUtil.ToastMessage(baseRequestActivity, error.desc);
                }
            } else {
                //提示网络连接异常
                DialogUtil.ToastMessage(baseRequestActivity, baseRequestActivity.getResources().getString(R.string.network_error));
            }
        }
    };

    protected void executeTokenFailue() {
        SharedPreferenceUtil.clearSP(baseRequestActivity, SharedPreferenceUtil.SP_NAME_USER);
        Intent intent = new Intent(baseRequestActivity, NormalHomeActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("content", "您的登陆信息已经失效，请重新登陆");
        DialogUtil.ToastMessage(baseRequestActivity, "您的登陆信息已经失效，请重新登陆");
        baseRequestActivity.startActivity(intent);
    }
	
	/*private final Listener<ResponseEntity> listener = new Listener<ResponseEntity>() {
		@Override
		public void onResponse(ResponseEntity response) {
			if(null != response.modelData.get("appVersionInfo")){
				app = JSON.parseObject(JSON.toJSONString(response.modelData.get("appVersionInfo")), AppUpdate.class);
				new AppUpdateDialog(baseRequestActivity).show();
			} else {
				if(check){
					Toast.makeText(baseRequestActivity, "当前是最新版本!", Toast.LENGTH_LONG).show();
				}
				checkUpdating = false;
			}
		}
	};
	
	private final ErrorListener errorListener = new ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			checkUpdating = false;
		}
	};*/

    /**
     * 下载任务
     *
     * @author xionganyin
     */
    class DownloadAsyncTask extends AsyncTask<String, Integer, File> {
        @Override
        protected File doInBackground(String... params) {
            try {
                File saveFile = new File(StorageUtil.getCacheDirectory(baseRequestActivity), "fqdf.apk");
                FileUtil.obbFile(saveFile);
                FileUtil.writeToFile(DownloadUtil.download(params[0]), saveFile);
                return saveFile;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(File result) {
            if (null != result) {
                Intent intent = new Intent(Intent.ACTION_VIEW);

                //判读版本是否在7.0以上
                if (Build.VERSION.SDK_INT >= 24) {
                    //provider authorities
                    Uri apkUri = FileProvider.getUriForFile(baseRequestActivity, "com.fqcar.fqdf.fileprovider", result);
                    //Granting Temporary Permissions to a URI
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
                }
                baseRequestActivity.startActivity(intent);
            } else {
                Toast.makeText(baseRequestActivity, "下载失败", Toast.LENGTH_LONG).show();
            }
            checkUpdating = false;
        }
    }

    /**
     * 更新Dialog
     *
     * @author xionganyin
     */
    class AppUpdateDialog extends Dialog {
        private final int TYPE_UPDATE_FORCE = 1;
        private TextView version_name, update_time, force_update_hint, update_content;
        private TextView cancel_update, immediately_update;

        public AppUpdateDialog(Context context, boolean cancelable,
                               OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        public AppUpdateDialog(Context context, int theme) {
            super(context, theme);
        }

        public AppUpdateDialog(Context context) {
            super(context);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.personal_center_update_version);
            //setCancelable(false);
            setCanceledOnTouchOutside(false);
            initView();
            initListener();
            initData();
        }

        @Override
        public void onBackPressed() {
        }

        private void initView() {
            version_name = (TextView) findViewById(R.id.version_num);
//			update_time = (TextView) findViewById(R.id.update_time);
            force_update_hint = (TextView) findViewById(R.id.force_update_hint);
            update_content = (TextView) findViewById(R.id.update_content);
            cancel_update = (TextView) findViewById(R.id.cancel_update);
            immediately_update = (TextView) findViewById(R.id.immediately_update);
        }

        private void initListener() {
            //取消更新
            cancel_update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != app) {
                        if (TYPE_UPDATE_FORCE == app.forceUpdate) {
                            VolleySingleton.getInstance().getRequestQueue().stop();
                            ((DFApp) baseRequestActivity.getApplication()).stopLocation();
                            System.gc();
                            System.exit(0);
                        }
                    }
                    dismiss();
                }
            });

            //立即更新
            immediately_update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != app) {
                        Toast.makeText(baseRequestActivity, "后台更新中，请稍候..", Toast.LENGTH_LONG).show();
                        new DownloadAsyncTask().execute(app.url);
                        immediately_update.setEnabled(false);
                    }
                    if (TYPE_UPDATE_FORCE != app.forceUpdate) {
                        dismiss();
                    }
                }
            });
        }

        private void initData() {
            if (null != app) {
                version_name.setText(app.versionName);
//				update_time.setText(DateTimeUtil.formatWithParten(app.createTime, "yyyy-MM-dd"));
                if (TYPE_UPDATE_FORCE == app.forceUpdate) {
                    force_update_hint.setVisibility(View.VISIBLE);
                }
                update_content.setText(app.changeLog);
            }
        }
    }
}